//
//  ZNBPanNavigationController.m
//  ZNB
//
//  Created by znb_iOS on 16/7/29.
//  Copyright © 2016年 znb. All rights reserved.
//

#import "ZNBPanNavigationController.h"
#import "ZNBPresentAnimator.h"
#import "ZNBDismissAnimator.h"

@interface ZNBPanNavigationController ()

@property (strong, nonatomic) UIPercentDrivenInteractiveTransition *interactionController;
@end

@implementation ZNBPanNavigationController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationBar.barTintColor = [UIColor whiteColor];
    [self.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : RGB_SAME(51),NSFontAttributeName : [UIFont systemFontOfSize:18]}];
    
    self.transitioningDelegate = self;
    UIScreenEdgePanGestureRecognizer *panGesture = [[UIScreenEdgePanGestureRecognizer alloc]initWithTarget:self action:@selector(panGestureAction:)];
    panGesture.edges = UIRectEdgeLeft;
    
//    [self.view addGestureRecognizer:panGesture];
}

- (void)panGestureAction:(UIScreenEdgePanGestureRecognizer *)panGesture
{
    CGPoint translation = [panGesture translationInView:panGesture.view.superview];
    CGFloat percent = translation.x / panGesture.view.bounds.size.width / 3;
//    NSLog(@"percent = %f", percent);
    switch (panGesture.state) {
            
        case UIGestureRecognizerStateBegan:
        {
            self.interactionController = [UIPercentDrivenInteractiveTransition new];
            [self dismissViewControllerAnimated:YES completion:nil];
            break;
        }
        case UIGestureRecognizerStateChanged:{
            [self.interactionController updateInteractiveTransition:percent];
            break;
        }
        case UIGestureRecognizerStateCancelled:
        case UIGestureRecognizerStateEnded:{
            if (percent > 0.17)
            {
                [self.interactionController finishInteractiveTransition];
            }
            else
            {
                [self.interactionController cancelInteractiveTransition];
            }
            self.interactionController = nil;
            break;
        }
        default:
            break;
    }
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source {
    return [ZNBPresentAnimator new];
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed {
    return [ZNBDismissAnimator new];
}

- (id<UIViewControllerInteractiveTransitioning>)interactionControllerForPresentation:(id<UIViewControllerAnimatedTransitioning>)animator {
    return nil;
}

- (id<UIViewControllerInteractiveTransitioning>)interactionControllerForDismissal:(id<UIViewControllerAnimatedTransitioning>)animator {
    return self.interactionController;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}

@end
